package com.ehais.util;

import static android.content.Context.MODE_PRIVATE;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.util.Log;

import com.ehais.api.NetConfig;
import com.ehais.modbuswifi.MyApplication;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtil{
    private static OkHttpClient mOkHttpClient = null;

    //Call this method in the Application class. ---> onCreate() method.
    //Thus we can get only one instance of httpClient in the whole app.
    public static void init(){
        if (mOkHttpClient == null) {
            OkHttpClient.Builder builder = new OkHttpClient().newBuilder()
                    .connectTimeout(5000, TimeUnit.MILLISECONDS)
                    .readTimeout(5000, TimeUnit.MILLISECONDS)
                    .writeTimeout(5000, TimeUnit.MILLISECONDS)
                    .sslSocketFactory(RxUtils.createSSLSocketFactory(),new RxUtils.TrustAllManager())
                    .hostnameVerifier(new RxUtils.TrustAllHostnameVerifier());
            SharedPreferences sharedPreferences= MyApplication.getInstance().getApplicationContext().getSharedPreferences("SharedData", Context.MODE_PRIVATE);
            String authorization = sharedPreferences.getString("Authorization","");
            if(authorization != null && !authorization.equals("") && authorization.length() > 0){
                builder.addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {

                        Request request = chain.request().newBuilder()
                                .addHeader("Authorization",authorization)
                                .build();
                        return chain.proceed(request);

                    }
                });
            }

            mOkHttpClient = builder.build();
        }
    }

    public static void reset(){
        mOkHttpClient = null;
    }


    //If GET method needs some other params, just need to add a HaspMap. Refer to:https://www.imooc.com/video/18685
    public static void get(String url, OkHttpCallBack okHttpCallback){
        Call call = null;

        try{
            Request request = new Request.Builder().url(NetConfig.BASE_URL + url).build();
            call = mOkHttpClient.newCall(request);
            call.enqueue(okHttpCallback);

        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public static void post(String url, Map<String, String> bodyMap, OkHttpCallBack okHttpCallback ){
        Call call = null;
        try{
            FormBody.Builder builder = new FormBody.Builder();
            for (HashMap.Entry<String, String> entry : bodyMap.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
            RequestBody body = builder.build();
            Request.Builder builderRequest = new Request.Builder();
            Request request = builderRequest.post(body).url(NetConfig.BASE_URL + url).build();
            init();



            List<Interceptor> interceptors = mOkHttpClient.interceptors();
            Log.i("OkHttpUtil","interceptors长度："+interceptors.size());


            call = mOkHttpClient.newCall(request);
            call.enqueue(okHttpCallback);

        }catch(Exception ex){
            ex.printStackTrace();
        }
    }


    public static void postEntity(String url, Map<String, String> bodyMap, OkHttpCallBack okHttpCallback ){
        Log.i("OkHttpUtil.URL","请求接口地址："+url);
        Call call = null;
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");//"类型,字节码"
        try{
            JSONObject json = new JSONObject(bodyMap);
            RequestBody body = RequestBody.create(mediaType,json.toString());
            Request.Builder builderRequest = new Request.Builder();
            Request request = builderRequest.post(body).url(NetConfig.BASE_URL + url).build();
            init();

            call = mOkHttpClient.newCall(request);
            call.enqueue(okHttpCallback);

        }catch(Exception ex){
            ex.printStackTrace();
        }
    }


    public static void postHasFile(String url, OkHttpCallBack okHttpCallback, HashMap<String, String> bodyMap, String filesKey, List<File> files){
        Call call = null;
        try{

            MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
            multipartBodyBuilder.setType(MultipartBody.FORM);
            for (HashMap.Entry<String, String> entry : bodyMap.entrySet()) {
                multipartBodyBuilder.addFormDataPart(entry.getKey(), entry.getValue());
            }
            //遍历paths中所有图片绝对路径到builder，并约定key如“upload”作为后台接受多张图片的key
            if (files != null){
                for (File file : files) {
                    multipartBodyBuilder.addFormDataPart(filesKey, file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
                }
            }
            RequestBody body = multipartBodyBuilder.build();
            Request.Builder builderRequest = new Request.Builder();
//            builderRequest.headers(new Headers())
            Request request = builderRequest.post(body).url(url).build();
            call = mOkHttpClient.newCall(request);
            call.enqueue(okHttpCallback);

        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

}
